from django.http import HttpResponseRedirect
from django.utils.deprecation import MiddlewareMixin
from stu_exam_manage.models import UserInfo
from django.conf import settings

from .logger_gf import Logging_gf   # 导入日志工具包

exclude_path = settings.EXCLUDE_URL
# 只有在登陆的情况下才能进行访问
class UserMiddleware(MiddlewareMixin):

    def process_request(self, request):
        # 排除不需要验证用户
        # print(exclude_path, request.path)
        # print(request.path.startswith('/admin'))
        if request.path.startswith('/admin'):
            ''' 排除管理员操作 '''
            return None
        if request.path in exclude_path:
            ''' 排除不需要验证的路径 '''
            return None

        # 获取并验证用户 id
        userid = request.session.get('userid', None)
        print('userid:', userid)
        if not userid:
            return HttpResponseRedirect('/user_verify/login.html')

        users = UserInfo.objects.filter(id = userid)
        if not users:
            return  HttpResponseRedirect('/user_verify/login.html')

        request.user = users[0]

        logging_path = settings.LOGGING_PATH[0]
        logger = Logging_gf(logging_path)
        current_user = UserInfo.objects.filter(id = request.session.get('userid', 0))[0]
        if request.path == r'/':
            logger.info(str('--->[' + current_user.username + ' ]--->[请求路径：' + request.path + ' ]'))